package com.camera.yl.v.models

import android.annotation.SuppressLint
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.camera.base.bean.CameraMark
import com.camera.base.util.ToastUtil
import com.camera.base.util.YLCameraConfig
import com.camera.base.v.models.BaseViewModel
import com.camera.base.v.models.SystemNavBarViewModel
import com.camera.yl.views.CameraManager.icpInterface
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class WatermarkSettingViewModel @Inject constructor(
    val systemNavBarViewModel: SystemNavBarViewModel
) : BaseViewModel() {
    companion object{
        public val TAG = "WatermarkSettingViewModel"
    }
    // 水印列表
    private val _watermarkList = MutableLiveData<List<CameraMark>>()
    val watermarkList: LiveData<List<CameraMark>> = _watermarkList
    
    // 当前选中的水印
    private val _currentWatermark = MutableLiveData<CameraMark>()
    val currentWatermark: LiveData<CameraMark> = _currentWatermark

    // 水印位置相关的LiveData
    val leftMargin: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>().apply { value = 10 }
    }
    val rightMargin: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>().apply { value = 10 }
    }
    val topMargin: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>().apply { value = 10 }
    }
    val downMargin: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>().apply { value = 10 }
    }

    // 下一个可用的水印ID
    private var nextWatermarkId = 1
    
    // 字体大小 - 修改为MutableLiveData以支持双向绑定
    val fontSize: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>().apply { value = 20 }
    }
    init {
        // 从SharedPreferences加载水印设置
        loadWatermarkSettings()
    }
    
    /**
     * 加载水印设置
     */
    @SuppressLint("LongLogTag")
    private fun loadWatermarkSettings() {
        try {
            val loadedList = YLCameraConfig.getCameraMarks()
            if (loadedList.isNotEmpty()) {
                _watermarkList.value = loadedList
                // 找到最大ID，用于设置下一个ID
                nextWatermarkId = loadedList.maxOf { it.index } + 1
                // 默认选中第一个水印
                selectWatermark(loadedList[0].index)
                return
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    
    /**
     * 选择水印
     * @param id 水印ID
     */
    @SuppressLint("LongLogTag")
    fun selectWatermark(id: Int) {
        val watermarkList = _watermarkList.value ?: return
        val watermark = watermarkList.find { it.index == id } ?: return
        _currentWatermark.value = watermark
        
        // 创建当前水印的副本，避免直接修改列表中的对象
        val watermarkCopy = CameraMark().apply {
            this.index = watermark.index
            this.content = watermark.content
            this.position = watermark.position
            this.size = watermark.size
            this.top_margin = watermark.top_margin
            this.bottom_margin = watermark.bottom_margin
            this.left_margin = watermark.left_margin
            this.right_margin = watermark.right_margin
            this.time = watermark.time
        }
        
        // 加载当前水印的设置
        // 将size (0-1范围) 转换为字体大小 (1-40范围)
        fontSize.value = (watermarkCopy.size * 100).toInt()
        
        // 将边距 (0-1范围) 转换为百分比 (0-100范围)
        leftMargin.value = (watermarkCopy.left_margin * 100).toInt()
        rightMargin.value = (watermarkCopy.right_margin * 100).toInt()
        topMargin.value = (watermarkCopy.top_margin * 100).toInt()
        downMargin.value = (watermarkCopy.bottom_margin * 100).toInt()
    }
    
    /**
     * 添加新水印
     */
    fun addWatermark() {
        val watermarkList = _watermarkList.value?.toMutableList() ?: mutableListOf()
        val newWatermark = CameraMark()
        newWatermark.index = nextWatermarkId
        newWatermark.type = 0 // 默认为自定义内容类型
        newWatermark.content = "新水印"
        newWatermark.position = 1 // 默认左上角位置
        newWatermark.size = 0.5f // 默认字体大小，范围0-1
        newWatermark.left_margin = 0.1f // 默认左边距10%
        newWatermark.right_margin = 0.1f // 默认右边距10%
        newWatermark.top_margin = 0.1f // 默认上边距10%
        newWatermark.bottom_margin = 0.1f // 默认下边距10%
        
        watermarkList.add(newWatermark)
        _watermarkList.value = watermarkList
        
        // 选中新添加的水印
        selectWatermark(nextWatermarkId)
        
        // 更新下一个ID
        nextWatermarkId++
    }

    
    /**
     * 更新当前水印位置
     */
    fun updateCurrentWatermarkPosition(position: Int) {
        val currentWatermark = _currentWatermark.value ?: return
        
        // 更新位置
        currentWatermark.position = position
        
        // 通知更改
        _currentWatermark.value = currentWatermark
    }
    
    /**
     * 更新当前水印文本内容
     * 只有当水印类型为0（自定义内容）时才有效
     */
    fun updateCurrentWatermarkText(text: String) {
        val currentWatermark = _currentWatermark.value ?: return
        
        // 只有自定义类型才更新内容
        if (currentWatermark.type == 0) {
            // 更新文本内容
            currentWatermark.content = text
            
            // 通知更改
            _currentWatermark.value = currentWatermark
        }
    }
    
    /**
     * 更新当前水印类型
     */
    fun updateCurrentWatermarkType(type: Int) {
        val currentWatermark = _currentWatermark.value ?: return
        
        // 更新类型
        currentWatermark.type = type
        
        // 如果不是自定义内容类型，清空content
        if (type != 0) {
            currentWatermark.content = ""
        }
        
        // 通知更改
        _currentWatermark.value = currentWatermark
    }
    
    /**
     * 保存水印设置
     */
    fun saveWatermarkSettings() {
        try {
            val watermarkList = _watermarkList.value?.toMutableList() ?: mutableListOf()
            val currentWatermark = _currentWatermark.value ?: return
            Log.e(TAG, "saveWatermarkSettings: "+currentWatermark.content )
            // 更新水印列表中的水印
            val index = watermarkList.indexOfFirst { it.index == currentWatermark.index }
            if (index != -1) {
                // 将当前编辑的水印复制到列表中
                watermarkList[index] = currentWatermark
                // 更新整个水印列表（仅在保存时执行）
                _watermarkList.value = watermarkList
                // 将水印列表保存到SharedPreferences
                YLCameraConfig.setCameraMarks(watermarkList as ArrayList<CameraMark>)
                icpInterface?.configMarksBeans()
                ToastUtil.showLong("水印设置已保存")
            } else {
                ToastUtil.showLong("保存失败：未找到对应的水印")
            }
        } catch (e: Exception) {
            ToastUtil.showLong("保存失败: ${e.message}")
        }
    }
    
    /**
     * 删除水印
     * @param id 要删除的水印ID
     */
    fun deleteWatermark(id: Int) {
        try {
            val watermarkList = _watermarkList.value?.toMutableList() ?: return
            
            // 查找要删除的水印索引
            val indexToRemove = watermarkList.indexOfFirst { it.index == id }
            if (indexToRemove == -1) {
                ToastUtil.showLong("删除失败：未找到对应的水印")
                return
            }
            
            // 从列表中移除
            watermarkList.removeAt(indexToRemove)
            
            // 更新列表
            _watermarkList.value = watermarkList
            
            // 如果列表不为空，选中第一项
            if (watermarkList.isNotEmpty()) {
                selectWatermark(watermarkList[0].index)
            } else {
                // 如果列表为空，添加一个新水印
                addWatermark()
            }
            
            // 保存更改到SharedPreferences
            YLCameraConfig.setCameraMarks(watermarkList as ArrayList<CameraMark>)
            icpInterface?.configMarksBeans()
            
            ToastUtil.showLong("水印已删除")
        } catch (e: Exception) {
            ToastUtil.showLong("删除失败: ${e.message}")
        }
    }
} 